package com.ruoyi.device.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.device.domain.DeviceInfo;
import com.ruoyi.device.domain.DeviceType;
import com.ruoyi.device.mapper.DeviceTypeMapper;
import com.ruoyi.device.service.IDeviceInfoService;
import com.ruoyi.device.service.IDeviceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @auth
 * @date
 */
@Service
public class DeviceTypeServicelmpl implements IDeviceTypeService {

    @Autowired(required = false)
    private DeviceTypeMapper typeMapper;

    @Autowired
    private IDeviceInfoService deviceService;

    /**
     * 查询设备分类
     * @param id
     * @return
     */
    @Override
    public DeviceType getTypeById(Long id) {
        return typeMapper.selectTypeById(id);
    }

    /**
     * 查询设备分类列表
     * @param params
     * @return
     */
    @Override
    public List<DeviceType> getTypeList(DeviceType params) {
        return typeMapper.selectTypeList(params);
    }

    /**
     * 新增设备分类
     * @param type
     * @return
     */
    @Override
    public int addType(DeviceType type) {
        return typeMapper.insertType(type);
    }

    /**
     * 修改设备分类
     * @param type
     * @return
     */
    @Override
    public int editType(DeviceType type) {
        return typeMapper.updateType(type);
    }

    /**
     * 批量删除设备分类
     * @param ids
     * @return
     */
    @Override
    public AjaxResult delTypeByIds(Long[] ids) {
        boolean noDelete = false;

        //遍历待删除的id数组
        for(long id : ids){
            //检测设备类别下是否有设备信息
            if(!chkDelete(id)){
                //只要有id不能删除，则把删除标识设置为true
                noDelete = true;
                //只要数组中有一个id不能删除，则跳出循环
                break;
            }
        }
        if(noDelete){
            return AjaxResult.warn("待删除的类别下有设备，删除失败");
        }else {
            int ret = typeMapper.deleteTypeByIds(ids);
            return ret > 0 ? AjaxResult.success() : AjaxResult.error();
        }
    }

    /**
     * 检测是否能够删除(列别下有设备则不能删除)
     * @param id 类别id
     * @return true可以删除
     */
    private boolean chkDelete(long id){
        DeviceInfo query = new DeviceInfo();
        query.setTypeId(id);
        List<DeviceInfo> list = deviceService.getDeviceList(query);
        return list == null || list.size() == 0;
    }

}
